from win32com.client import Dispatch
import pythoncom
import zipfile
import tkinter
from tkinter import messagebox
from tkinter import ttk
from tkinter import filedialog
import os
import sys
import time
import shutil
import _thread
progressbar=""
def create_shortcut(target_path, shorcut_path,install_path):
    shell = Dispatch('WScript.Shell')
    shortcut = shell.CreateShortcut(shorcut_path)
    shortcut.TargetPath = target_path
    shortcut.WorkingDirectory=install_path
    shortcut.Save()
def resource_path(relative_path):
    if getattr(sys, 'frozen', False): #是否Bundle Resource
        base_path = sys._MEIPASS
    else:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

def is_wpp_dir(check_path):
    file_c = ["Main.exe","starter.exe","wppRunner.exe","base_library.zip","FFmpeg","char","wallpaper","main_ui.html"]
    is_n = 0
    for exe_c in file_c:
        if os.path.exists(os.path.join(check_path,exe_c)):
            is_n+=1
    if is_n >= len(file_c)/2:
        return True
    else:
        return False

def select_dir():
    global need_del,install_path
    install_path_input = filedialog.askdirectory()
    if os.path.exists(install_path_input):
        if os.listdir(install_path_input)==[] or is_wpp_dir(install_path_input)==True:
            install_path = install_path_input
            path_v.set(install_path)
            return
    if install_path_input[-1] == "/":
        dir_name = "cv_wallpaper"
    else:
        dir_name = "/cv_wallpaper"
    if not os.path.exists(install_path_input+dir_name):
        os.makedirs(install_path_input+dir_name)
    path_v.set(install_path_input+dir_name)
    install_path=install_path_input+dir_name
def start_install():
    global download_inf_bar,download_inf_var,progressbar,install_started
    install_started=True
    path_input_frame.destroy()
    start_btn.pack_forget()
    progressbar=ttk.Progressbar(window)
    progressbar.pack()
    #设置进度条最大值为100
    progressbar['maximum']=100
    #设置进度条长度
    progressbar['length']=500
    download_inf_var = tkinter.StringVar()
    download_inf_bar = tkinter.Label(window,textvariable=download_inf_var)
    download_inf_bar.place(x=50,y=290)
    download_inf_var.set("准备开始安装...")
    window.update()
    _thread.start_new_thread(install,())
def install():
    global download_inf_var,install_started,progressbar
    try:
        progressbar["mode"]="indeterminate"
        progressbar["orient"]=tkinter.HORIZONTAL
        if not os.path.exists(install_path):
            os.makedirs(install_path)
        if os.listdir(install_path)!=[]:
            download_inf_var.set("正在删除文件")
            exe_list = ["Main.exe","starter.exe","wppRunner.exe","char_runner.exe"]
            for exe in exe_list:
                os.popen("taskkill /F /im "+exe)
                download_inf_var.set("正在删除文件 停止进程"+exe)
            download_inf_var.set("正在删除文件")
            un_delDir_list=["wallpaper","plug","char"]
            for filename in os.listdir(install_path):
                file_path = os.path.join(install_path, filename)
                if os.path.isfile(file_path):
                    if not ".json" in file_path:
                        os.remove(file_path)
                        download_inf_var.set("正在删除: "+file_path)
                else:
                    can_del_s = False
                    for dir in un_delDir_list:
                        if dir in file_path:
                            can_del_s=True
                            break
                    if can_del_s==True:
                        shutil.rmtree(file_path)
                        download_inf_var.set("正在删除文件夹: "+file_path)
            # shutil.rmtree(install_path)
            # print("正在删除目录："+install_path)
            # os.makedirs(install_path)

        progressbar["mode"]="determinate"
        filename = resource_path(os.path.join("res","wpp_pack.zip"))
        download_inf_var.set("正在解压文件")
        with zipfile.ZipFile(filename, 'r') as zip_ref:
            total_files = len(zip_ref.infolist())
            extracted_files = 0
            for file in zip_ref.infolist():
                extracted_files += 1
                if not os.path.exists(file.filename):
                    zip_ref.extract(file, install_path)
                progress = (extracted_files / total_files) * 100
                progress_num = int(progress)
                progressbar['value']=int(progress_num)
                download_inf_var.set("正在解压文件 "+str('[解压进度]: '+str(progress_num)+"%"))
                # print(f"Extracting: {file.filename} - Progress: {progress:.2f}%")
            # zip_ref.extractall(install_path)
        plug_pack = resource_path(os.path.join("res","wpp-plug_pack.zip"))
        plug_dir = os.path.join(install_path,"plug")
        if os.path.exists(plug_pack):
            for filename in os.listdir(plug_dir):
                file_path = os.path.join(plug_dir, filename)
                if os.path.isfile(file_path):
                    if not ".json" in file_path:
                        os.remove(file_path)
            with zipfile.ZipFile(plug_pack, 'r') as zip_ref:
                zip_ref.extractall(plug_dir)
        download_inf_var.set("正在创建快捷方式")

        pythoncom.CoInitialize()
        if os.path.exists(os.path.join(os.path.expanduser("~"), "Desktop","梦幻空间.lnk")):
            os.remove(os.path.join(os.path.expanduser("~"), "Desktop","梦幻空间.lnk"))
        desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop')
        target_path = os.path.join(install_path,"Main.exe")
        shortcut_path = os.path.join(desktop_path, '梦幻空间.lnk')
        create_shortcut(target_path, shortcut_path,install_path)
        pythoncom.CoUninitialize()

        download_inf_var.set("完成")
        install_started=False
        show_finish()
    except Exception as e:
        messagebox.showerror("梦幻空间 - 安装时出现错误",e)
        install_started=False
def out():
    window.quit()
def show_finish():
    progressbar.pack_forget()
    download_inf_bar.place_forget()
    tkinter.Button(window,text="完成",width=20,height=2,font=("微软雅黑", 20),command=out).pack()
def closeWindow():
    if install_started == True:
        messagebox.showerror("警告","正在进行安装，请不要退出")
        return
    window.quit()
have_network=False
install_path = "C:/Program Files/wallpaper"

install_started = False
window = tkinter.Tk()
window.title("梦幻空间 - 安装")
window.geometry("600x400")
window.resizable(False,False)
logo_img = tkinter.PhotoImage(file=resource_path(os.path.join("res","mhkj_logo.png"))) 
tkinter.Label(window, image=logo_img).pack(anchor="center")
path_input_frame = tkinter.Frame(window)
path_v = tkinter.StringVar()
path_v.set("C:/Program Files/wallpaper")
tkinter.Label(path_input_frame,textvariable=path_v,width=50,height=2,bg="white").pack(side="left")
tkinter.Button(path_input_frame,text="浏览",width=5,height=2,command=select_dir).pack(side="right")
path_input_frame.pack()
start_btn=tkinter.Button(window,text="开始安装",width=20,height=1,font=("微软雅黑", 20),command=start_install)
start_btn.pack()
window.protocol('WM_DELETE_WINDOW', closeWindow)
window.mainloop()